package com.agrm.rabc.controller;


import com.agrm.model.common.dtos.ResponseResult;
import com.agrm.model.rabc.dto.RolePermMapping;
import com.agrm.rabc.service.RolePermMappingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping(value = "/api/v1/role_perms", produces = MediaType.APPLICATION_JSON_VALUE)
public class RolePermMappingApi {
    private RolePermMappingService rolePermMappingService;

    @Autowired
    public void setRolePermMappingService(RolePermMappingService rolePermMappingService) {
        this.rolePermMappingService = rolePermMappingService;
    }

    @GetMapping
    public ResponseResult findAll(RolePermMapping rpm) {
        List<RolePermMapping> mappings = rolePermMappingService.findAll(rpm);
        return ResponseResult.okResult(mappings);
    }

    @GetMapping("/id/{id}")
    public ResponseResult findById(@PathVariable("id") Integer id) {
        RolePermMapping rpm = rolePermMappingService.findById(id);
        if (rpm == null) {
            return ResponseResult.errorResult(-1,"未查询到指定编号的角色-权限关联");
        } else {
            return ResponseResult.okResult(rpm);
        }
    }

    @PostMapping
    public ResponseResult save(@RequestBody RolePermMapping rpm) {
        boolean success = rolePermMappingService.save(rpm);
        if (success) {
            return ResponseResult.okResult(200,"");
        } else {
            return ResponseResult.errorResult(-1,"保存角色-权限关联失败");
        }
    }

    @PutMapping
    public ResponseResult update(@RequestBody RolePermMapping rpm) {
        boolean success = rolePermMappingService.update(rpm);
        if (success) {
            return ResponseResult.okResult(200,"");
        } else {
            return ResponseResult.errorResult(-1,"修改角色-权限关联失败");
        }
    }

    @DeleteMapping
    public ResponseResult deleteByIds(@RequestBody Integer[] ids) {
        int count = rolePermMappingService.deleteByIds(List.of(ids));
        if (count > 0) {
            return ResponseResult.okResult(count);
        } else {
            return ResponseResult.errorResult(-1,"删除角色-权限关联失败");
        }
    }
}
